package corp.edu.amadeus.utils.file;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;

public class FileUtils {

	public static void binaryTransferm(OutputStream fO, byte[] data)
		throws IOException {
		fO.write(data, 0, data.length);
		fO.flush();
		fO.close();
	}

	public static void eraseFiles(String folder_path) {
	    File folder = new File(folder_path);
	    for(File file : folder.listFiles()) {
		if(!file.isFile()) {
		    continue;
		}
		file.delete();
	    }
	}

	public static byte[] extractContent(InputStream is) throws Exception {
		BufferedInputStream buffer = new BufferedInputStream(is);
		int BUFFER_SIZE = 8192;
		byte data[] = new byte[BUFFER_SIZE];
		int count;
		ByteArrayOutputStream dest = new ByteArrayOutputStream();
		while ((count = buffer.read(data, 0, BUFFER_SIZE)) != -1) {
			dest.write(data, 0, count);
		}
		dest.flush();
		buffer.close();
		is.close();
		return dest.toByteArray();
	}

	public static byte[] extractFileContent(File source) throws Exception {
		if (!source.exists()) {
			throw new Exception("El fichero ubicado en "
					+ source.getAbsolutePath() + " NO existe");
		}
		FileInputStream fis = new FileInputStream(source);
		BufferedInputStream buffer = new BufferedInputStream(fis);
		int BUFFER_SIZE = 8192;
		byte data[] = new byte[BUFFER_SIZE];
		int count;
		ByteArrayOutputStream dest = new ByteArrayOutputStream();
		while ((count = buffer.read(data, 0, BUFFER_SIZE)) != -1) {
			dest.write(data, 0, count);
		}
		dest.flush();
		fis.close();
		return dest.toByteArray();
	}

	public static String extractFileExtension(String filename) {
		String[] aux;
		String extension = "";
		if (filename.indexOf(".") == -1) {
			extension = filename;
		} else {
			aux = filename.split("[.]");
			extension = aux[aux.length-1];
		}
		return extension;
	}

	public static String removeFileExtension(String filename) {
		String[] aux;
		String nameWithoutExt = "";
		if (filename.indexOf(".") == -1) {
			nameWithoutExt = filename;
		} else {
			aux = filename.split("[.]");
			nameWithoutExt = aux[0];
		}
		return nameWithoutExt;
	}

}